package com.wxxymaker.edu.controller;

import com.blade.ioc.annotation.Inject;
import com.blade.kit.StringKit;
import com.blade.mvc.annotation.Path;
import com.blade.mvc.annotation.PathParam;
import com.blade.mvc.annotation.PostRoute;
import com.blade.mvc.ui.RestResponse;
import com.wxxymaker.edu.model.entity.TestPaper;
import com.wxxymaker.edu.roles.TeacherRoles;
import com.wxxymaker.edu.service.TestPaperService;
import com.wxxymaker.edu.utils.FileUtils;

/**
 * @AUTHOR soft
 * @DATE 2018/10/11 22:42
 * @DESCRIBE 试卷处理器
 */
@TeacherRoles
@Path(value = "/course/set/paper", restful = true)
public class TestPaperSetHandler {

    @Inject
    private TestPaperService testPaperService;

    @PostRoute("/:kid/create")
    public RestResponse create(@PathParam Integer kid,
                               TestPaper paper) {
        paper.setCourseId(kid);
        String tempPath = paper.getPath();
        this.changeFileDown(paper, kid);
        TestPaper testPaper = testPaperService.add(paper);
        if (testPaper != null) {
            FileUtils.saveTemp(tempPath);
            return RestResponse.ok(testPaper);
        }
        return RestResponse.fail();
    }

    @PostRoute("/:kid/change")
    public RestResponse change(@PathParam Integer kid,
                               TestPaper paper) {
        Integer id     = paper.getId();
        String  path   = paper.getPath();
        this.changeFileDown(paper, kid);
        if (testPaperService.change(paper)) {
            paper.setId(id);
            FileUtils.saveTemp(path);
            return RestResponse.ok(paper);
        }
        return RestResponse.fail();
    }

    @PostRoute("/:kid/delete/:tpid")
    public RestResponse delete(@PathParam Integer kid,
                               @PathParam Integer tpid) {
        TestPaper delete = testPaperService.delete(tpid);
        if (delete != null) {
            return RestResponse.ok(delete);
        }
        return RestResponse.fail();
    }

    private void changeFileDown(TestPaper paper, Integer kid) {
        String format = "/file/download?t=%s&k="+kid+"&d=%s";
        String path   = paper.getPath();
        String result = paper.getResult();
        if (StringKit.isNotBlank(path) && !path.startsWith("/file/download")) {
            paper.setPath(String.format(format, 1, paper.getFolder()));
        }
        if (StringKit.isNotBlank(result) && !result.startsWith("/file/download")) {
            paper.setResult(String.format(format, 2, paper.getFolder()));
        }
    }
}
